package firstSocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class MySocket {
	
	private static int port = 80;
//	private static String ip = "220.181.111.86";
	
	private static Socket socket = null;
//	private static OutputStream os = null;
	private static PrintWriter out = null;
	private static BufferedReader in = null;
	
	
	public static void main(String args[]) {

		try {
			socket = new Socket(InetAddress.getByName("http://www.google.com.hk/"), port);
//			socket = new Socket(ip, port);
//			os = socket.getOutputStream();
			boolean autoflush = true;
			out = new PrintWriter(socket.getOutputStream(), autoflush);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.println("GET / HTTP/1.1");
		out.println("Host: www.google.com.hk");
		out.println("Connection: keep-alive");
		out.println();

		boolean loop = true;
		StringBuffer sb = new StringBuffer(8096);
		try {
			while (loop) {
				if (in.ready()) {
					int i = 0;
					while (i != -1) {
						i = in.read();
						sb.append((char) i);
					}
					loop = false;
				}
				try {
					Thread.currentThread();
					Thread.sleep(50);
				} catch (InterruptedException e) {

					e.printStackTrace();
				}
			}

			System.out.println(sb.toString());
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
